#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from datetime import datetime
import calendar
import sys

reload(sys)
sys.setdefaultencoding("utf-8")
def json_convert():
    # data = abc.get("data")
    # if data is not None:
    #     del abc["data"]

    res = {}
    # 取出原json其他数据并放到返回结果中
    # for k in abc:
    #     res[k] = abc[k]
    #
    # # 如果data为空返回空json
    # if data is None:
    #     res["data"] = {}
    #     return json.dumps(res, ensure_ascii=False)

    newData = data.copy()

    # 增值税小规模申报信息
    syptZzsXgm = getJsonArray(data.get("syptZzsXgm"))
    for item in syptZzsXgm:
        try:
            nd = item.get("ND")
            yf = item.get("YF")
            if int(yf) in [3, 6, 9, 12]:
                add_period(item, nd, yf, "season")
            else:
                add_period(item, nd, yf, "month")
        except:
            continue
    newData["syptZzsxgm"] = syptZzsXgm

    syptGsdjxx = getJsonArray(data.get("syptGsdjxx"))
    if isinstance(syptGsdjxx, list) and len(syptGsdjxx) > 0:
        ND = syptGsdjxx[0].get("ND")
        kyslrq = ND + "-01-01" if ND is not None and len(ND) == 4 else ""
    else:
        kyslrq = ""
    newData["syptSwdjxx"][0]["kyslrq"] = kyslrq

    # 增值税一般纳税人申报
    syptZzsybnsr = getJsonArray(data.get("syptZzsybnsr"))
    for item in syptZzsybnsr:
        try:
            nd = item.get("ND")
            yf = item.get("YF")
            add_period(item, nd, yf, "month")
        except:
            continue
    newData["syptZzsybnsr"] = syptZzsybnsr

    # 所得税A类月、季申报
    syptQysdsA1 = getJsonArray(data.get("syptQysdsA1"))
    for item in syptQysdsA1:
        try:
            nd = item.get("ND")
            yf = item.get("YF")
            if int(yf) in [3, 6, 9, 12]:
                add_period(item, nd, yf, "season")
            else:
                add_period(item, nd, yf, "month")
        except:
            continue
    newData["syptQysdsA1"] = syptQysdsA1

    # 所得税A类年报
    syptQysdsNd = getJsonArray(data.get("syptQysdsNd"))
    for item in syptQysdsNd:
        try:
            nd = item.get("ND")
            add_period(item, nd, 12, "month")
        except:
            continue
    newData["syptQysdsNd"] = syptQysdsNd


    res["data"] = newData
    return json.dumps(res, ensure_ascii=False)


def isfloat(x):
    try:
        if isinstance(float(x), float):
            if str(x) in ["inf", "infinity", "INF", "INFINITY", "True"]:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def add_period(item, nd, yf, item_type):
    if item is not None and isfloat(nd) and isfloat(yf) and isinstance(item, dict):
        firstDayWeekDay, monthRange = calendar.monthrange(int(nd), int(yf))
        end = datetime(int(nd), int(yf), monthRange)
        if item_type == "year":
            yf = int(yf) - 11
        elif item_type == "season":
            yf = int(yf) - 2
        else:
            yf = int(yf)
        start = datetime(int(nd), yf, 1)
        item["skssqq"] = start.strftime('%Y-%m-%d')
        item["skssqz"] = end.strftime('%Y-%m-%d')
    elif isinstance(item, dict):
        item["skssqq"] = ""
        item["skssqz"] = ""
    return item


def getJsonArray(jsonArr):
    try:
        return jsonArr if isinstance(jsonArr, list) else []
    except:
        return []


if __name__ == "__main__":
    file_obj = open(r"../data/TX_GZ_DSJ.json", "r")
    content = file_obj.read()
    abc = json.loads(content, strict=False)
    aa = json_convert()
    print aa

result = json_convert()
